package com.langyiquan.front.controller;

import com.alipay.api.internal.util.AlipaySignature;
import com.langyiquan.config.AliPayResource;
import com.langyiquan.entity.WxPayResult;
import com.langyiquan.enums.OrderStatus;
import com.langyiquan.service.OrderService;
import com.langyiquan.utils.XmlUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@ApiIgnore
@RequestMapping(value = "/payment/notice")
public class PaymentNotifyController {

	@Autowired
	private AliPayResource aliPayResource;

	@Autowired
	private OrderService orderService;

	@RequestMapping(value="/wxpay")
	public void wxpay(HttpServletRequest request, HttpServletResponse response) throws Exception {

		// 获取微信支付结果
		BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream()));
		String result = "";
		String line;
		while ((line = in.readLine()) != null) {
			result += line;
		}
		WxPayResult payResult = (WxPayResult)XmlUtil.xml2Object(result, WxPayResult.class);

		boolean isPaid = payResult.getReturn_code().equals("SUCCESS") ? true : false;

		PrintWriter writer = response.getWriter();
		if (isPaid) {

			String orderId = payResult.getOut_trade_no();			// 商户订单号

			// ====================== 操作商户自己的业务，比如修改订单状态等 start ==========================
			orderService.updateOrderStatus(orderId, OrderStatus.WAIT_DELIVER.type);

			// 通知微信已经收到消息
			String noticeStr = XmlUtil.setXML("SUCCESS", "");
			writer.write(noticeStr);
			writer.flush();

		} else {

			// 支付失败
			String noticeStr = XmlUtil.setXML("FAIL", "");
			writer.write(noticeStr);
			writer.flush();
		}

	}

	@RequestMapping(value="/alipay")
	public String alipay(HttpServletRequest request, HttpServletResponse response) throws Exception {

		//获取支付宝POST过来反馈信息
		Map<String,String> params = new HashMap<String,String>();
		Map<String,String[]> requestParams = request.getParameterMap();
		for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
			String name = iter.next();
			String[] values = requestParams.get(name);
			String valueStr = "";
			for (int i = 0; i < values.length; i++) {
				valueStr = (i == values.length - 1) ? valueStr + values[i]
						: valueStr + values[i] + ",";
			}
			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
			params.put(name, valueStr);
		}

		boolean signVerified = AlipaySignature.rsaCheckV1(params,
														aliPayResource.getAlipayPublicKey(),
														aliPayResource.getCharset(),
														aliPayResource.getSignType()); //调用SDK验证签名

		if(signVerified) {

			// 商户订单号
			String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
			// 交易状态
			String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

			if (trade_status.equals("TRADE_SUCCESS")){
				orderService.updateOrderStatus(out_trade_no, OrderStatus.WAIT_DELIVER.type);
			}

			return "success";
		}else {
			return "fail";
		}
	}


}
